import json
import random
from typing import TextIO

from proto import user_pb2, user_pb2_grpc

from loguru import logger


logger.add(sink='access.log', rotation='00:00', enqueue=True)


class UserService(user_pb2_grpc.UserService):

    def UserList(self, request, context, *args, **kwargs):
        with open('users.txt', 'r', encoding='utf8') as f:
            users = f.read().split('\n')
        resp = user_pb2.UserListResponse()
        logger.info(f'request: {request}')
        page = request.page or 1
        page_size = request.pageSize or 2
        start = page_size * (page - 1)
        end = page_size * page
        if end > len(users):
            end = -1
        resp.total = len(users)
        for u in users[start: end]:
            u = json.loads(u)
            user = user_pb2.UserInfoResponse()
            user.id = u['id']
            user.name = u['name']
            user.gender = u['gender']
            resp.data.append(user)
        return resp

    def Register(self, request, context, *args, **kwargs):
        logger.info(f'request register: {request}')
        uid = random.randint(1, 9999)
        user = dict(id=uid, name=request.name, gender=request.gender, password=request.password, repeatd=request.repeatPassword)
        resp = user_pb2.UserRegisterResponse()
        with open('users.txt', 'a', encoding='utf8') as f:
            f.write(json.dumps(user, ensure_ascii=False))
            f.write('\n')
        resp.id = uid
        resp.name = user['name']
        resp.gender = user['gender']
        return resp
